import { Inject, Injectable } from '@nestjs/common';
import { CreateYingshishipinDto } from './dto/create-yingshishipin.dto';
import { UpdateYingshishipinDto } from './dto/update-yingshishipin.dto';
import { Like, Repository } from 'typeorm';
import { Yingshishipin } from './entities/yingshishipin.entity';
import { SearchPagesDto } from './dto/search-pages.dto';
import { BusinessException } from 'src/common/exceptions/business.exception';
import { ShipinleibieService } from '../shipinleibie/shipinleibie.service';

@Injectable()
export class YingshishipinService {
  constructor(
    @Inject('YINGSHISHIPIN_REPOSITORY')
    private yingshishipinRepository: Repository<Yingshishipin>,
    private readonly shipinleibieService: ShipinleibieService,
  ) {}

  async create(createDto: CreateYingshishipinDto) {
    try {
      const entity = this.yingshishipinRepository.create(createDto);
      if (createDto.leibieId) {
        const shipinleibie = await this.shipinleibieService.findOne(
          createDto.leibieId,
        );
        if (shipinleibie) {
          entity.shipinleibie = shipinleibie;
        }
      }
      return await this.yingshishipinRepository.save(entity);
    } catch (error) {
      throw new Error(`创建失败: ${error.message}`);
    }
  }

  findAll() {
    return this.yingshishipinRepository.find({
      relations: ['shipinleibie'], // 如果有类别关联
    });
  }
  statistics() {
    return this.yingshishipinRepository
      .createQueryBuilder('shipin')
      .leftJoin('shipin.shipinleibie', 'leibie') // 关联分类表
      .select('leibie.leibie', 'categoryName') // 分类名称字段为 leibie.leibie
      .addSelect('COUNT(shipin.id)', 'videoCount')
      .groupBy('leibie.id') // 按分类 ID 分组
      .getRawMany();
  }

  async findAllPage(pages: SearchPagesDto) {
    const {
      page = 1,
      limit = 10,
      shipinbianhao,
      shipinmingcheng,
      leibie,
    } = pages;
    const skip = (page - 1) * limit;

    const where: Record<string, any> = {};

    if (shipinbianhao) {
      where.shipinbianhao = Like(`%${shipinbianhao}%`);
    }
    if (shipinmingcheng) {
      where.shipinmingcheng = Like(`%${shipinmingcheng}%`);
    }
    if (leibie) {
      where.shipinleibie = { leibie: Like(`%${leibie}%`) };
    }

    try {
      const [list, total] = await this.yingshishipinRepository.findAndCount({
        where,
        skip,
        take: limit,
        order: { createTime: 'DESC' },
        relations: ['shipinleibie'], // 如果有类别关联
      });

      return {
        list: list.map((item) => {
          const result = { ...item } as any;
          if (item.shipinleibie) {
            result.leibieId = item.shipinleibie.id;
            result.leibie = item.shipinleibie.leibie;
            delete result.shipinleibie;
          }
          return { ...result };
        }),
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit),
      };
    } catch (error) {
      console.log(error);
    }
  }

  findOne(id: number) {
    return this.yingshishipinRepository.findOne({
      where: { id },
      relations: ['shipinleibie'], // 如果有类别关联
    });
  }

  async update(id: number, updateDto: UpdateYingshishipinDto) {
    // 创建事务确保数据一致性
    return this.yingshishipinRepository.manager.transaction(async (manager) => {
      const entity = await manager.findOne(Yingshishipin, {
        where: { id },
        relations: ['shipinleibie'],
      });

      if (!entity) {
        throw new BusinessException('视频资源不存在');
      }

      // 处理类别更新逻辑
      if (updateDto.leibieId) {
        // 通过类别名称查找
        const leibieEntity = await this.shipinleibieService.findOne(
          updateDto.leibieId,
        );

        if (!leibieEntity) {
          throw new BusinessException('指定类别不存在');
        }
        entity.shipinleibie = leibieEntity;
      }

      // 合并其他更新字段
      Object.assign(entity, updateDto);

      // 保存更新
      await manager.save(Yingshishipin, entity);

      // 返回最新数据
      return manager.findOne(Yingshishipin, {
        where: { id },
        relations: ['shipinleibie'],
      });
    });
  }
  remove(id: number) {
    return this.yingshishipinRepository.delete(id);
  }

  async batchRemove(ids: number[]) {
    const result = await this.yingshishipinRepository
      .createQueryBuilder()
      .delete()
      .whereInIds(ids)
      .execute();

    return {
      message: `成功删除 ${result.affected} 条记录`,
      affected: result.affected,
    };
  }
}
